package com.lcy.smartcity.controller;

import com.lcy.smartcity.dto.BuildingsDTO;
import com.lcy.smartcity.entity.Buildings;
import com.lcy.smartcity.service.BuildingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buildings")
@CrossOrigin(origins = "http://localhost:5173")

public class BuildingsController {

    @Autowired
    private BuildingsService buildingsService;

    /**
     * 根据建筑物ID查询建筑物信息
     *
     * @param id 建筑物的唯一标识符
     * @return 查询到的建筑物对象
     */
    @GetMapping("/{id}")
        public BuildingsDTO findById(@PathVariable Integer id) {
            Buildings buildings = buildingsService.findById(id).orElse(null);

            return getBuildingsDTO(buildings);
    }



    /**
     * 根据建筑物名称进行模糊搜索
     *
     * @param name 建筑物名称关键词
     * @return 匹配的建筑物列表
     */
    @GetMapping("/search")
    public List<BuildingsDTO> searchByName(@RequestParam String name) {
        List<Buildings> buildingsList= buildingsService.SearchByName(name);
        return buildingsList.stream().map(buildings -> {
            return getBuildingsDTO(buildings);
        }).collect(Collectors.toList());
    }

    @GetMapping("/searchHotel")
    public List<BuildingsDTO> searchHotelByName(@RequestParam String name) {
        List<Buildings> buildingsList = buildingsService.SearchHotelByName(name);
        return buildingsList.stream().map(buildings -> {
            return getBuildingsDTO(buildings);
        }).collect(Collectors.toList());
    }

    // 根据经纬度和距离返回酒店
    @GetMapping("/searchBuildingsWithinDistance")
    public List<BuildingsDTO> searchAroundHotel(
            @RequestParam("longitudeX") Double longitudeX,
            @RequestParam("latitudeY") Double latitudeY,
            @RequestParam("distance") Double distance) {
        List<Buildings> buildingsWithinDistance = buildingsService.findBuildingsWithinDistance(longitudeX, latitudeY, distance);
        return buildingsWithinDistance.stream().map(this::getBuildingsDTO).toList();
    }

    public BuildingsDTO getBuildingsDTO(Buildings buildings) {

        BuildingsDTO dto = new BuildingsDTO();

        dto.setId(buildings.getId());
        dto.setName(buildings.getName());
        dto.setFloor(buildings.getFloor());
        dto.setHeight(buildings.getHeight());
        dto.setType(buildings.getType());
        dto.setCategory(buildings.getCategory());
        dto.setDistance(buildings.getDistance());

        if (buildings.getGeo() != null) {
            dto.setLongitude_X(buildings.getGeo().getX());
            dto.setLatitude_Y(buildings.getGeo().getY());
        } else {
            // geo 为空时 fallback 到原始字段
            dto.setLongitude_X(buildings.getLongitude_X());
            dto.setLatitude_Y(buildings.getLatitude_Y());
        }
        return dto;
    }
}
